package com.enmonster.binding;

import com.enmonster.annotations.*;
import com.enmonster.commons.InterResolveCommon;
import com.enmonster.executor.InsertExecutor;
import com.enmonster.executor.SelectExecutor;
import com.enmonster.resolve.original.ModelOriginal;
import com.enmonster.resolve.original.ResultOriginal;

import java.lang.annotation.Annotation;
import java.lang.reflect.*;

/**
 * @Author wuxi
 * @create 2019/4/9 上午11:07
 */
public class MyInvocationHandler implements InvocationHandler {

    private Object obj;

    private ResultOriginal resultOriginal = new ResultOriginal ();


    private ModelOriginal modelOriginal = new ModelOriginal();

    public MyInvocationHandler(Object object){
        this.obj = object;
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("使用动态代理接口方法开始..."+method.getName());

        //初始化sql
        initSql(method);

        //解析WxParam注解 获取代理对象参数名
        InterResolveCommon.wxParamResolve(method,modelOriginal,args);

        System.out.println(modelOriginal.toString());

        return geResult(method);
    }


    public void initSql(Method method) {
        Annotation[] annotations = method.getAnnotations();
        for (Annotation annotation : annotations){
            Class ann = annotation.annotationType();
            if(WxSelect.class.equals(ann)){
                InterResolveCommon.wxSelectResolve(method,modelOriginal);
            }else if(WxInsert.class.equals(ann)){
                InterResolveCommon.wxInsertResolve(method,modelOriginal);
            }else if(WxResults.class.equals(ann)){
                InterResolveCommon.wxResultsResolve(method,resultOriginal);
            }else if(WxResult.class.equals(ann)){
                InterResolveCommon.wxResultResolve(method,resultOriginal);
            }
        }
    }


    public Object geResult(Method method) throws Throwable {
        Object obj = new Object();
        switch (modelOriginal.getType()){
            case SELECT:
                obj = new SelectExecutor().executor(modelOriginal,  method ,  resultOriginal);
                break;
            case INSERT:
                 obj = new InsertExecutor().executor(modelOriginal,  method ,  resultOriginal);
                break;
            case DELETE:
                break;
            case UPDATE:
                break;
            default:
        }
        return obj;
    }



}
